package com.yiyun.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yiyun.blog.dao.mapper.TagMapper;
import com.yiyun.blog.dao.pojo.Tag;
import com.yiyun.blog.service.TagService;
import com.yiyun.blog.vo.Result;
import com.yiyun.blog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;

import java.util.List;

/**
 * @author Bao
 * @create 2022-01-01-23:14
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    // 根据文章id获取标签
    @Override
    public List<TagVo> findTagsByArticleId(Long articleId) {
        //mybatisplus 无法进行多表查询
        List<Tag> tags = tagMapper.findTagsByArticleId(articleId);
        return copyList(tags);
    }

    private List<TagVo> copyList(List<Tag> tagList) {
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;

    }

    private TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        BeanUtils.copyProperties(tag, tagVo);
        tagVo.setId(String.valueOf(tag.getId()));
        return tagVo;
    }

    // 查询最热标签
    @Override
    public Result hot(int limit) {
        /**
         * 最热标签
         * 1.标签拥有的文章数量最多 最热标签
         * 2.查询 根据tag_id 分组 计数，从小到大 排列 取前 limit个
         * */
        List<Long> tagIds = tagMapper.findHotTagIds(limit);
        if (CollectionUtils.isEmpty(tagIds)){
            return Result.fail(404,"查不到");
        }
        //需要的是tagId 和 tagname Tag对象
        //select * from tag where id in (1,2,3,4)
        List<Tag> tagList = tagMapper.findTagsByTagIds(tagIds);
        return Result.success(tagList);
    }

    // 查询所有文章标签
    @Override
    public Result findAllTag() {

        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.select(Tag::getId,Tag::getTagName);
        List<Tag> tagList = tagMapper.selectList(queryWrapper);
        List<TagVo> tagVoList = copyList(tagList);
        return Result.success(tagVoList);
    }

    // 查询所有文章标签的detail
    @Override
    public Result findAllTagDetail() {

        List<Tag> tagList = tagMapper.selectList(new LambdaQueryWrapper<>());
       List<TagVo> tagVoList = copyList(tagList);
        return Result.success(tagVoList);
    }

    // 通过id查找标签detail
    @Override
    public Result findTagDetailById(Long tagId) {

        Tag tag = tagMapper.selectById(tagId);
        TagVo tagVo = copy(tag);
        return Result.success(tagVo);
    }

}
